package com.xuhuan.thread.study2.syn;

/**
 * @author huan.xu
 * @date 2021/9/29 16:28
 * @description 买票
 */
public class BuyTicketDemo {
    public static void main(String[] args) {
        Station station = new Station();

        new Thread(station, "张三").start();
        new Thread(station, "李四").start();
        new Thread(station, "王五").start();
    }
}

/**
 * 车站
 */
class Station implements Runnable {
    /**
     * 剩余票数
     */
    private int ticketNums = 10;
    /**
     * 线程退出标记
     */
    private boolean flag = true;

    @Override
    public void run() {
        while (flag) {
            buyTicket();
        }
    }

    private synchronized void buyTicket() {
        if (ticketNums <= 0) {
            flag = false;
            return;
        }
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "--->买到了" + ticketNums--);
    }


}